package com.ogilvy.audi.security;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 11-8-8
 * Time: 下午4:36
 * To change this template use File | Settings | File Templates.
 */
public class MyUsernamePasswordAuthenticationFilter extends GenericFilterBean {
        protected final Log log = LogFactory.getLog(getClass());
   public static final String VALIDATE_CODE = "validateCode";
      private String filterProcessesUrl = "/j_security_check";
     private String authenticationFailureUrl;


//    protected String obtainSessionValidateCode(HttpSession session) {
//        Object obj = session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//        return null == obj ? "" : obj.toString();
//    }

      private String obtainValidateCodeParameter(HttpServletRequest request) {
        Object obj = request.getParameter(VALIDATE_CODE);
        return null == obj ? "" : obj.toString();
    }



    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        log.debug("Entering loginFilter method") ;
         HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;
           if (!requiresAuthentication(request, response)) {
              chain.doFilter(request, response);
              return;
            }

         HttpSession session = request.getSession();
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //String sessionValidateCode = obtainSessionValidateCode(session);
        //让上一次的验证码失效
//        session.setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, null);
//        String validateCodeParameter = obtainValidateCodeParameter(request);
//        log.debug("The sessionValidateCode is "+sessionValidateCode) ;
//        log.debug("The validateCodeParameter is "+validateCodeParameter) ;
//        if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {
//            log.debug("validate is error") ;
//             response.sendRedirect(request.getContextPath() +  getAuthenticationFailureUrl());
//        }


    chain.doFilter(request, response);
    }

      private boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response)
  {
    String uri = request.getRequestURI();
      log.debug("The uri is "+uri) ;
    int pathParamIndex = uri.indexOf(';');

    if (pathParamIndex > 0) {
      uri = uri.substring(0, pathParamIndex);
    }
    if ("".equals(request.getContextPath())) {
      return uri.endsWith(getFilterProcessesUrl());
    }
    return uri.endsWith(request.getContextPath() + getFilterProcessesUrl());
  }

    public String getAuthenticationFailureUrl() {
        return authenticationFailureUrl;
    }

    public void setAuthenticationFailureUrl(String authenticationFailureUrl) {
        this.authenticationFailureUrl = authenticationFailureUrl;
    }

    public String getFilterProcessesUrl() {
        return filterProcessesUrl;
    }

    public void setFilterProcessesUrl(String filterProcessesUrl) {
        this.filterProcessesUrl = filterProcessesUrl;
    }
}
